package com.niuwa.p2p.core.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.niuwa.p2p.core.manager.DictManager;
import com.niuwa.p2p.entity.Dictionary;

/**
 * 
 * @author zzf
 *
 */
public abstract class DictUtil {

    private static Logger log = Logger.getLogger(DictUtil.class);

    private static Map<String, List<Dictionary>> dictMap = DictManager
            .getInstance().getDictMap();

    /**
     * 根据字典类型加载字典列表
     * 
     * @param dictType
     *            字典类型
     * @return
     */
    public static List<Dictionary> getDictionaryByDictType(String dictType) {
        if (null == dictMap) {
            if (log.isDebugEnabled()) {
                log.info("数据字典没有加载！");
            }
            return null;
        }
        if (!dictMap.containsKey(dictType)) {
            if (log.isDebugEnabled()) {
                log.info("没有【" + dictType + "】类型的数据字典！");
            }
            return null;
        }
        return dictMap.get(dictType);
    }

    /**
     * 根据字典类型和字典码获取字典名
     * 
     * @param dictType
     * @param dictCode
     * @return
     */
    public static String getDictNameByTypeAndCode(String dictType,
            String dictCode) {
        if (StringUtils.isNotBlank(dictType)
                && StringUtils.isNotBlank(dictCode)) {
            List<Dictionary> list = getDictionaryByDictType(dictType);
            if (!CollectionUtils.isEmpty(list)) {
                for (Dictionary dict : list) {
                    if (dict.getDictCode().endsWith(dictCode)) {
                        return dict.getDictName();
                    }
                }
            }
        }
        return "";
    }

    /*
     * 根据字典的PARENT_DICT_ID返回所有子字典集
     * 
     * @param parentDictId
     * @param dictType
     */
    public static List<Dictionary> getDictListByParentDictId(
            String parentDictId, String dictType) {
        List<Dictionary> resultList = new ArrayList<Dictionary>();
        if (StringUtils.isNotBlank(parentDictId)) {
            List<Dictionary> list = getDictionaryByDictType(dictType);
            if (!CollectionUtils.isEmpty(list)) {
                for (Dictionary dict : list) {
                    if (dict.getParentDictId() == Integer.parseInt(parentDictId)) {
                        resultList.add(dict);
                    }
                }
            }
        }
        return resultList;
    }
}
